package com.mapaower.admin.controller;

import com.mapaower.admin.service.AdminUserService;
import com.mapaower.admin.utils.ResponseResult;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/admin/auth")
public class AuthController {

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Value("${jwt.expiration}")
    private int jwtExpiration;

    @Value("${jwt.header}")
    private String jwtHeader;

    @Value("${jwt.prefix}")
    private String jwtPrefix;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private AdminUserService adminUserService;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public ResponseEntity<ResponseResult<?>> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");

        try {
            // 进行身份验证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, password)
            );

            // 设置认证信息到Spring Security上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 生成JWT令牌
            String token = generateToken(authentication);

            // 构建响应数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("token", jwtPrefix + " " + token);
            responseData.put("tokenType", "Bearer");
            responseData.put("expiresIn", jwtExpiration);

            return ResponseEntity.ok(ResponseResult.success("登录成功", responseData));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ResponseResult.error("用户名或密码错误"));
        }
    }

    /**
     * 生成JWT令牌
     */
    private String generateToken(Authentication authentication) {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        return Jwts.builder()
                .setSubject(userDetails.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + jwtExpiration))
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact();
    }

    /**
     * 管理员退出登录
     */
    @PostMapping("/logout")
    public ResponseEntity<ResponseResult<?>> logout() {
        // 清除Spring Security上下文
        SecurityContextHolder.clearContext();
        return ResponseEntity.ok(ResponseResult.success("退出登录成功"));
    }

    /**
     * 获取当前登录用户信息
     */
    @PostMapping("/current-user")
    public ResponseEntity<ResponseResult<?>> getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            return ResponseEntity.ok(ResponseResult.success(userDetails));
        } else {
            return ResponseEntity.status(401).body(ResponseResult.error("未授权"));
        }
    }
}